import { _decorator, Component, instantiate, Node, Prefab, Rect, Sprite, SpriteFrame, tween, UITransform, Vec3 } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('Block')
export class Block extends Component {
    spriteIndex: number = 0;
    spriteFrame: SpriteFrame = null;
    origin: Block = null;
    tmpPosition: Vec3 = new Vec3();
    addLayer3Time: number = 0;

    setAddLayer3Time() {
        this.addLayer3Time = new Date().getTime();
    }
    getAddLayer3Time() {
        return this.addLayer3Time;
    }
    show() {
        this.node.getChildByName('y_shadow').active = false;
    }
    hide() {
        this.node.getChildByName('y_shadow').active = true;
    }
    getBoundingBox(): Rect {
       const rect1 =  this.node.getComponent(UITransform).getBoundingBox();
       const num = 10;
       return new Rect(rect1.x + 10, rect1.y + 10, rect1.width - 2 * num, rect1.height - 2 * num)
    }
    setSprite(spriteFrame: SpriteFrame){
        this.spriteFrame = spriteFrame;
    }

    getSpriteFrame() {
        return this.spriteFrame;
    }
    refreshSprite() {
        const position = this.node.position.clone();
        tween(this.node)
        .to(0.2, { position: new Vec3(0) })
        .call(() => {
            this.node.getChildByName('y_body').getComponent(Sprite).spriteFrame = this.spriteFrame;
        })
        .to(0.2, { position: position })
        .start();
    }
    setSpriteIndex(index: number) {
        this.spriteIndex = index;
    }

    getSpriteIndex() {
        return this.spriteIndex;
    }

    canTouch() {
        return !this.node.getChildByName('y_shadow').active;
    }

    playStartTouch() {
        tween(this.node).to(0.1, {
            scale: new Vec3(1, 1, 1)
        }).start();
    }

    payEndTouch() {
        tween(this.node).to(0.1, {
            scale: new Vec3(0.8, 0.82, 1)
        }).start();
    }   

    cloneBlock(parent: Node, blockPrefab: Prefab) {
        const newBlock = instantiate(blockPrefab);
        newBlock.setParent(parent);
        newBlock.getChildByName('y_body').getComponent(Sprite).spriteFrame = this.spriteFrame;
        const worldPosition = this.node.getWorldPosition();
        const localPosition = parent.getComponent(UITransform).convertToNodeSpaceAR(worldPosition);
        newBlock.setPosition(localPosition);
        const blockScript = newBlock.getComponent(Block);
        blockScript.setSprite(this.spriteFrame);
        blockScript.origin = this;
        blockScript.show();
        this.node.active = false;
        return blockScript;
    }

    getTmpPosition():Vec3 {
        return this.tmpPosition;
    }

    setTmpPosition(pos: Vec3) {
        this.tmpPosition = pos;
    }
}


